package com.pig4cloud.pig.api.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class MapUtils {

	private static Logger logger = LoggerFactory.getLogger(MapUtils.class);
	
	public static boolean isEmpty(Map map) {
        return (map == null || map.isEmpty());
    }
	
	/**
	 * @param paramsMap
	 * @return
	 */
	public static String queryString(Map<String, String> paramsMap) {
		if (paramsMap == null || paramsMap.size() == 0) {
			return "";
		}
		StringBuilder result = new StringBuilder();
		for (Entry<String, String> entry : paramsMap.entrySet()) {
			result.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
		}
		String rs = result.toString();
		return rs.substring(0, rs.length() - 1);
	}

	/**
	 * 通过Map 的 key 排序
	 * 
	 * @param map
	 * @return
	 */
	public static Map<String, String> sortMapByKey(Map<String, String> map) {
		if (map == null || map.isEmpty()) {
			return null;
		}
		Map<String, String> sortMap = new TreeMap<String, String>(new Comparator<String>() {
			@Override
			public int compare(String o1, String o2) {
				return o1.compareTo(o2);
			}
		});
		sortMap.putAll(map);
		return sortMap;
	}
	
	
	public static byte[] convertRequestToByte(HttpServletRequest request) {
    	byte[] bytes = null;
    	try {
    		Map<String, String[]> reqMap = request.getParameterMap();
    		Map<String, String> rtMap = new TreeMap<String, String>(new MapKeyComparator());
    		if (reqMap == null || reqMap.isEmpty()) {
    			return null;
    		}
    		for (Entry<String, String[]> entry : reqMap.entrySet()) {
    			rtMap.put(entry.getKey().toLowerCase(), StringUtils.killNull(entry.getValue()[0]));
    		}
    		
    		ByteArrayOutputStream byt = new ByteArrayOutputStream();
    		ObjectOutputStream ops = new ObjectOutputStream(byt);

    		ops.writeObject(rtMap);

    		bytes = byt.toByteArray(); 
		} catch (Exception e) {
			logger.error("map到byte[]转换异常",e);
		}
        
        return bytes;
    }
	
	
	public static byte[] convertRequestToByte(HttpServletRequest request, Map<String, String> otMap) {
		byte[] bytes = null;
		try {
			Map<String, String[]> reqMap = request.getParameterMap();
			Map<String, String> rtMap = new TreeMap<String, String>(new MapKeyComparator());
			if (reqMap == null || reqMap.isEmpty()) {
				return null;
			}
			for (Entry<String, String[]> entry : reqMap.entrySet()) {
				rtMap.put(entry.getKey().toLowerCase(), StringUtils.killNull(entry.getValue()[0]));
			}
			rtMap.putAll(otMap);
			logger.info("all data : {}", rtMap);
			ByteArrayOutputStream byt = new ByteArrayOutputStream();
			ObjectOutputStream ops = new ObjectOutputStream(byt);
			
			ops.writeObject(rtMap);
			
			bytes = byt.toByteArray(); 
		} catch (Exception e) {
			logger.error("map到byte[]转换异常",e);
		}
		
		return bytes;
	}
	
	
	public static byte[] convertMapToByte(Map<String, Object> otMap) {
		byte[] bytes = null;
		try {
			if (otMap == null || otMap.isEmpty()) {
				return null;
			}
			
			ByteArrayOutputStream byt = new ByteArrayOutputStream();
			ObjectOutputStream ops = new ObjectOutputStream(byt);
			
			ops.writeObject(otMap);
			
			bytes = byt.toByteArray(); 
		} catch (Exception e) {
			logger.error("map到byte[]转换异常",e);
		}
		
		return bytes;
	}
	
	
	public static byte[] convertStringMapToByte(Map<String, String> otMap) {
		byte[] bytes = null;
		try {
			if (otMap == null || otMap.isEmpty()) {
				return null;
			}
			
			ByteArrayOutputStream byt = new ByteArrayOutputStream();
			ObjectOutputStream ops = new ObjectOutputStream(byt);
			
			ops.writeObject(otMap);
			
			bytes = byt.toByteArray(); 
		} catch (Exception e) {
			logger.error("map到byte[]转换异常",e);
		}
		
		return bytes;
	}
	
	/**
	 * 将形如key1=value1&key2=value2的字符串数据转为map
	 * @param qryStr
	 * @return
	 */
	public static Map<String, String> convertQueryStringToMap(String qryStr) {
		Map<String, String> rtMap = new TreeMap<String, String>(new MapKeyComparator());
    	try {
    		if (StringUtils.isBlank(qryStr))
    			return null;
    		
    		String[] qryArray = qryStr.split("&");
    		
    		if (qryArray != null){
    			for (String qrys : qryArray) {
    				String[] qryay = qrys.split("=");
    				if (qryay == null) continue;
    				
    				if (qryay.length != 2) {
    					logger.error("请确保数据格式形如：key1=value1&key2=value2");
    					continue;
    				}
    				
    				rtMap.put(qryay[0], qryay[1]);
    			}
    		}
		} catch (Exception e) {
			logger.error("queryString到map转换异常",e);
		}
        return rtMap;
    }
	
	public static Map<String, Object> convertByteToMap(byte[] bytes) {
		Map<String, Object> rtMap = new TreeMap<String, Object>(new MapKeyComparator());
		try {
			ByteArrayInputStream byteInt=new ByteArrayInputStream(bytes);
			ObjectInputStream objInt=new ObjectInputStream(byteInt);
			
			rtMap = (Map<String, Object>) objInt.readObject();
		} catch (Exception e) {
			logger.error("byte[]到map转换异常",e);
		}
		return rtMap;
	}
	
	public static Map<String, String> convertByteToStrMap(byte[] bytes) {
		Map<String, String> rtMap = new TreeMap<String, String>(new MapKeyComparator());
		try {
			ByteArrayInputStream byteInt=new ByteArrayInputStream(bytes);
			ObjectInputStream objInt=new ObjectInputStream(byteInt);
			
			rtMap = (Map<String, String>) objInt.readObject();
		} catch (Exception e) {
			logger.error("byte[]到map转换异常",e);
		}
		return rtMap;
	}
	
}
